<template>
  <div class="addPayee">
    <div class="title">设置结算卡</div>
    <!-- <div class="title">{{this.$route.query.id?'编辑银行卡信息':'添加银行卡'}}</div> -->
    <div class="content">
      <div class="left">
        <!-- <div class="hint">
          商户可添加多个结算卡，但当前使用只可选择一个结算卡。
        </div> -->
        <div class="card">
          <div class="top">
            <div class="l">
              <img
                :src="require('@/assets/imgs/bank/' + this.bankImg + '.png')"
                alt=""
              />
              <div>{{ bankname }}</div>
            </div>
            <div class="r">
              <img src="@/assets/imgs/setting/right.png" alt="" />
            </div>
          </div>
          <div class="number">
            <span :class="inputTag ? 'light' : ''">{{ numberText }}</span>
          </div>
          <div class="footer">
            <div class="name" :class="inputTagName ? 'light' : ''">
              {{ nameText }}
            </div>
            <img src="@/assets/imgs/setting/add_foot.png" alt="" />
          </div>
        </div>
      </div>
      <div class="right">
        <el-form
          :model="form"
          ref="form"
          :rules="ruleForm"
          label-width="130px"
          label-position="top"
        >
          <el-form-item label="账户类型" prop="bankAcctType">
            <el-radio-group
              v-model="form.bankAcctType"
              @change="bankAcctTypeChange"
            >
              <el-radio label="1">对公账户</el-radio>
              <el-radio label="2">对私账户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="开户银行" prop="bankCode">
            <el-select
              v-model="form.bankCode"
              placeholder="请选择"
              class="width512"
              @change="setName"
            >
              <el-option
                v-for="item of bankList"
                :key="item.id"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="银行账号" prop="cardNo">
            <el-input
              :disabled="this.$route.query.id ? true : false"
              v-model="form.cardNo"
              placeholder="请输入"
              class="width512"
              maxlength="19"
              @input="textInputNum"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="账户名称" prop="cardName">
            <el-input
              v-model="form.cardName"
              placeholder="请输入"
              class="width512"
              maxlength="50"
              @input="textInputName"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="所在地"
            :required="true"
            v-if="form.bankAcctType == '1'"
          >
            <div style="display: flex; margin-bottom: -20px">
              <el-form-item label-width="0"  prop="provCode">
                <el-select
                  v-model="form.provCode"
                  placeholder="请选择省"
                  @change="handleProv"
                  style="width: 213px; margin-right: 7px"
                >
                  <el-option
                    v-for="item of provList"
                    :key="item.id"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0" prop="areaCode">
                <el-select
                  v-model="form.areaCode"
                  placeholder="请选择市"
                  @change="handleArea"
                  style="width: 213px; margin-left: 7px"
                >
                  <el-option
                    v-for="item of cityList"
                    :key="item.id"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form-item>
          <el-form-item
            label="开户银行许可证"
            prop="cardPhoto"
            v-if="form.bankAcctType === '1'"
          >
            <el-upload
              drag
              action="/merchantApi/oss/upload"
              :limit="2"
              list-type="picture"
              :headers="{
                auth_token: getToken(),
                auth_tmp: curTmp,
                auth_tck: curTck,
              }"
              :file-list="cardPhoto"
              :on-success="(res, file) => handleSuccess(res, file, 'cardPhoto')"
              :on-error="
                (err, file) => {
                  //console.log(err);
                }
              "
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text2">单击或将文件拖到该区域以上传</div>
              <div class="el-upload__tip2">
                支持 PNG或JPG，最大不可超过2M
                <!-- Support PDF, PNG, JPG and other files upload -->
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="手机号" prop="cardTel">
            <el-input
              :disabled="this.$route.query.id ? true : false"
              v-model.number="form.cardTel"
              placeholder="请输入手机号"
              class="width512"
              maxlength="11"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="身份证号"
            prop="certId"
            v-show="form.bankAcctType === '2'"
          >
            <el-input
              v-model="form.certId"
              placeholder="请输入身份证号"
              class="width512"
            >
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="开户银行全称">
            <el-input
              v-model="form.bankNickname"
              placeholder="请输入开户银行全称"
              class="width512"
            >
            </el-input>
          </el-form-item> -->
          <el-form-item label="" style="margin-top: 50px">
            <el-button
              class="width120"
              @click="() => this.$backTo(`/account/wallet`)"
              >返回</el-button
            >
            <el-button type="primary" class="width120" @click="handleSubmit"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- <div class="bankWrap">
      <img src="@/assets/imgs/setting/bank.png" class="bankImg" />
      <div>
        <div class="addTitle">添加收款银行卡，随时提现账户余额或转账</div>
        <div class="hint">
          每个商户最多可添加10个收款银行卡，但只可使用1个收款银行卡
        </div>
      </div>
    </div> -->
  </div>
</template>

<script>
import { isMobile, isIdCard, isBankCard } from "@/utils/validate";
import { getToken } from "@/utils/public";
import crypto from "@/crypto";
import { randomWord } from "@/utils/getRandom";

export default {
  name: "settingAddPayee",
  data() {
    const checkCardNo = (rule, value, callback) => {
      if (isBankCard(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的银行账号"));
      }
    };
    const checkPhone = (rule, value, callback) => {
      if (isMobile(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的手机号码"));
      }
    };
    const checkIdCard = (rule, value, callback) => {
      if (this.form.bankAcctType === "1") {
        callback();
      }
      if (isIdCard(value)) {
        callback();
      } else {
        callback(new Error("请输入合法的身份证号"));
      }
    };
    return {
      curTmp: null,
      curTck: null,
      len: [8, 9, 10, 11, 12][
        Math.floor(Math.random() * [8, 9, 10, 11, 12].length)
      ],
      provList: [],
      cityList: [],
      bankList: [],
      cardPhoto: [],
      form: {
        bankAcctType: "1",
      },
      ruleForm: {
        bankAcctType: [
          { required: false, message: "请选择账户类型", trigger: "change" },
        ],
        cardName: [
          { required: true, message: "请输入账户名称", trigger: "change" },
          { max: 50, message: "最大长度50字符", trigger: "change" },
        ],
        cardNo: [
          {
            required: this.$route.query.id ? false : true,
            message: "请输入银行账号",
            trigger: "change",
          },
          {
            validator: this.$route.query.id ? "" : checkCardNo,
            trigger: "change",
          },
        ],
        certId: [
          { required: false, message: "请输入身份证号", trigger: "change" },
          { validator: checkIdCard, trigger: "change" },
        ],
        bankCode: [
          { required: true, message: "请选择开户银行", trigger: "change" },
        ],
        cardTel: [
          {
            required: this.$route.query.id ? false : true,
            message: "请输入手机号",
            trigger: "change",
          },
          {
            validator: this.$route.query.id ? "" : checkPhone,
            trigger: "change",
          },
        ],
        cardPhoto: [{ required: true, validator: this.checkFile }],
        provCode: [
          {
            required: true,
            message: "请选择省",
            trigger: "change",
          },
        ],
        areaCode: [
          {
            required: true,
            message: "请选择市",
            trigger: "change",
          },
        ],
      },
      bankname: "开户银行",
      bankImg: "add_img",
      numberText: "**** **** **** ****",
      nameText: "账户名称",
      inputTag: false,
      inputTagName: false,
    };
  },
  created() {
    this.curTmp = new Date().getTime();
    this.curTck = crypto.set(
      getToken() + "_" + this.curTmp + "_" + randomWord(this.len),
      "a1g0qoalvv19aed3"
    );
    this.getInfo();
    // 省
    this.$http
      .get(
        "/dictdata/getByDictTypeAndPid?dictType=ada_bank_province_city&parentId=1"
      )
      .then((res) => {
        if (res.code === "0000") {
          this.provList = res.data;
        }
      });
    // 银行
    this.$http
      .get("dictdata/getByDictType?dictType=adapay_bank_code")
      .then((res) => {
        if (res.code === "0000") {
          this.bankList = res.data;
          //console.log(this.bankList);
        }
      });
  },
  methods: {
    beforeUpload(file) {
      const is2M = file.size / 1024 / 1024 < 2;
      const type = ["image/jpg", "image/png", "image/jpeg"].includes(file.type);

      if (!type) {
        this.$message.warning("上传图片只支持jpg、png格式");
        return false;
      }
      if (!is2M) {
        this.$message.warning("上传图片大小不能超过2M");
        return false;
      }
      return true;
    },
    textInputNum(val) {
      if (val.length) {
        this.numberText = val;
        this.inputTag = true;
      } else {
        this.numberText = "**** **** **** ****";
        this.inputTag = false;
      }
    },
    textInputName(val) {
      if (val.length) {
        this.nameText = val;
        this.inputTagName = true;
      } else {
        this.nameText = "账户名称";
        this.inputTagName = false;
      }
    },
    resetText() {
      this.bankname = "开户银行";
      this.bankImg = "add_img";
      this.numberText = "**** **** **** ****";
      this.nameText = "账户名称";
      this.inputTag = false;
      this.inputTagName = false;
    },
    handleRemove() {
      this.form.cardPhoto = "";
    },
    handleArea(val) {
      this.$set(this.form, this.form.areaCode, val);
    },
    bankAcctTypeChange(val) {
      if (this.$route.query.id) {
        this.form = {
          bankAcctType: val,
          cardTel: this.form.cardTel,
          cardNo: this.form.cardNo,
        };
      } else {
        this.form = {
          bankAcctType: val,
        };
      }
      this.$refs.form.resetFields();
      this.resetText();
      if (val === "1") {
        this.ruleForm.certId[0].required = false;
        this.ruleForm.provCode[0].required = true;
        this.ruleForm.areaCode[0].required = true;
      } else {
        this.ruleForm.certId[0].required = true;
        this.ruleForm.provCode[0].required = true;
        this.ruleForm.areaCode[0].required = true;
      }
    },
    getToken,
    setName(val) {
      const obj = this.bankList.find((v) => v.dictValue === val);
      this.form.bankName = obj.dictLabel;

      this.bankname = obj.dictLabel;
      this.bankImg = obj.dictValue;
    },
    getInfo() {
      const id = this.$route.query.id;
      // 列表页面跳转过来
      if (id) {
        this.$http
          .get(`/api/merchant/memberbank/get`, {
            params: { id },
          })
          .then((res) => {
            if (res.code === "0000") {
              this.form = res.data;
              var areaCode = res.data.areaCode;
              this.handleProv(res.data.provCode);
              this.$set(this.form, "areaCode", areaCode);
              this.$http
                .get(`/oss/get?id=${res.data.cardPhoto}`)
                .then((res_) => {
                  this.cardPhoto = [
                    {
                      name: res_.name,
                      url:
                        window.location.origin +
                        `/merchantApi/oss/view?id=${res.data.cardPhoto}`,
                    },
                  ];
                });
            }
          });
      }
    },
    // 省
    handleProv(val) {
      // this.$refs.form.validate();
      this.$set(this.form, "areaCode", "");
      // setTimeout(() => {
      //   this.$refs.form.clearValidate(["areaCode"]);
      // }, 0);
      this.$http
        .get(
          `/dictdata/getByDictTypeAndPid?dictType=ada_bank_province_city&parentId=${val}`
        )
        .then((res) => {
          if (res.code === "0000") {
            this.cityList = res.data;
          }
        });
    },
    // 获取市
    getCityList(val, prop) {
      this.$http
        .get(
          `/dictdata/getByDictTypeAndPid?dictType=ada_bank_province_city&parentId=${val}`
        )
        .then((res) => {
          if (res.code === "0000") {
            this[prop] = res.data.map((item) => item);
          }
        });
    },
    checkFile(rule, value, callback) {
      const prop = rule.field;
      if (this.form[prop]) {
        callback();
      } else {
        callback(new Error("请上传开户银行许可证"));
      }
    },
    handleSuccess(res, file, prop) {
      if (res.code === "0000") {
        this[prop] = [file];
        this.form[prop] = res.data.id;
              setTimeout(() => {
        this.$refs.form.clearValidate(["cardPhoto"]);
      }, 0);
        // this.$refs.form.validate();
      } else {
        this[prop] = [];
        this.$message.warning(res.msg);
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.$route.query.id) {
            this.$http
              .put("/api/merchant/memberbank/edit", {
                ...this.form,
                payformChannel: "ada",
                cardTel: "",
                cardNo: "",
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message({
                    message: "修改成功",
                    type: "success",
                    duration: 500,
                    onClose: () => {
                      this.$backTo(`/setting/payeeAccount`);
                    },
                  });
                }
              });
          } else {
            //console.log(this.form);
            this.$http
              .post("/api/merchant/settleaccount/add", {
                ...this.form,
                channel: "ada",
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$router.push("/setting/payeeResult");
                  // this.$message({
                  //   message: "添加成功",
                  //   type: "success",
                  //   duration: 500,
                  //   onClose: () => {
                  //     // this.$backTo(`/account/wallet`);
                  //     this.$router.push("/setting/payeeResult");
                  //   },
                  // });
                } else {
                  //console.log(res);
                  this.$router.push({
                    path: "/setting/payeeResult",
                    query: {
                      msg: res.msg,
                    },
                  });
                }
              });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.addPayee {
  padding: 70px 95px 125px 95px;
  background: #fff;
  min-width: 1200px;

  .bankWrap {
    display: flex;
    margin: 40px 0 70px 0px;
    .bankImg {
      width: 126px;
      height: 60px;
      margin-right: 30px;
    }
    .addTitle {
      font-size: 18px;
      line-height: 32px;
    }
  }

  .title {
    font-size: 24px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #1d1c1c;
    margin-bottom: 20px;
    // line-height: 33px;
  }

  .width512 {
    width: 440px;
  }
  .content {
    display: flex;
    .left {
      margin-right: 195px;
      .hint {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;
      }
      .card {
        width: 446px;
        background: #eef4fa;
        border-radius: 18px;
        margin-top: 100px;
        padding: 36px 40px;
        .top {
          display: flex;
          justify-content: space-between;
          .l {
            display: flex;
            align-items: center;
            img {
              width: 38px;
              border-radius: 38px;
              margin-right: 18px;
            }
            span {
              font-size: 18px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #4f595f;
            }
          }
          .r {
            line-height: 38px;
            img {
              width: 16px;
            }
          }
        }
        .number {
          margin-top: 45px;
          span {
            font-size: 20px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #869daa;
            letter-spacing: 3px;
          }
          span.light {
            font-size: 24px;
            color: #1d1c1c;
          }
        }

        .footer {
          display: flex;
          justify-content: space-between;
          margin-top: 40px;
          .name {
            max-width: 325px;
            word-wrap: break-word;
            margin-top: 19px;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #869daa;
          }
          .name.light {
            font-size: 18px;
            color: #4f595f;
          }
          img {
            width: 66px;
            height: 42px;
          }
        }
      }
    }
    .right {
      :deep(.el-form-item__content) {
        line-height: 20px;
      }
      :deep(.el-upload .el-upload-dragger) {
        width: 440px;
        height: 100px;
      }
      :deep(.el-icon-upload) {
        font-size: 30px;
        margin-top: 20px;
        line-height: 10px;
      }
      :deep(.el-upload__text2) {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
      }
      :deep(.el-upload__tip2) {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #bfbfbf;
      }
    }
  }
}
</style>
